package com.wwu.system.common.security;

import com.wwu.common.constant.SecurityConst;
import com.wwu.common.web.CaptchaObj;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/** 登陆验证码校验过滤器
 * @author 一蓑烟雨
 * @version 1.0.0
 * @date 2023-06-03 22:02
 */
@Component
public class SecurityCaptchaVerifyFilter extends OncePerRequestFilter {
    /** 登陆操作 */
    public  static  final  String  IS_LOGIN = "/login";
    /** 登陆请求为POST */
    public  static  final  String  LOGIN_METHOD = "post";
    /** 登陆失败处理器 */
    @Resource
    private SecurityLoginFailedHandler securityLoginFailedHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //请求为登陆时执行过滤器
        if(request.getRequestURI().indexOf(IS_LOGIN)>-1 && LOGIN_METHOD.equalsIgnoreCase(request.getMethod())){
            //获取前端传入的验证码参数
            String captchaCode = request.getParameter("captcha");
            //获取session中存入的验证码实体
            CaptchaObj captchaObj = (CaptchaObj) request.getSession().getAttribute(SecurityConst.CAPTCHA);
            try{
                //进行验证码判断
                if(!StringUtils.hasText(captchaCode)){
                    throw new InsufficientAuthenticationException("验证码不能为空");
                }
                if(null == captchaObj){
                    throw new InsufficientAuthenticationException("验证码不存在");
                }
                if(captchaObj.isExpired()){
                    throw new InsufficientAuthenticationException("验证码已过期");
                }
                if(!captchaObj.getCaptcha().verify(captchaCode)){
                    throw new InsufficientAuthenticationException("验证码不正确");
                }
            }catch (InsufficientAuthenticationException e) {
                //发生异常后交给登陆失败处理器
                securityLoginFailedHandler.onAuthenticationFailure(request,response,e);
                return;
            }
        }
        //放行后续流程
        filterChain.doFilter(request, response);
    }
}
